#!/bin/bash
# ctl_common.sh - version 1.1
#
# Bash script which contains common functions shared with other scripts.
# If you have a common function that can be added in here, please do so.
#
# He is how this script gets included in another script:
#   SRC=$(cd $(dirname "$0"); pwd)
#   source "${SRC}/ctl_common.sh"
#
# Notes:
# - This script calls the user bash_profile to set the environment variables,
# useful when used to execute a script in a cron job.
#
# change logs:
#   1.0: (hicham.x.medkouri@jpmorgan.com), intial version 
#	1.1: (hicham.x.medkouri@jpmorgan.com), added _log, _get_pid and _running 
#		 util methods.

# Debugging: Disabled by default.
#set -x

# set environment variable defined in bash_profile
# this is needed when invoking the scripts from crontab
. $HOME/.bash_profile

# resolve links - $0 may be a softlink
PRG="$0"

while [ -h "$PRG" ]; do
  ls=`ls -ld "$PRG"`
  link=`expr "$ls" : '.*-> \(.*\)$'`
  if expr "$link" : '/.*' > /dev/null; then
    PRG="$link"
  else
    PRG=`dirname "$PRG"`/"$link"
  fi
done

# Get standard environment variables
PRGDIR=`dirname "$PRG"`

# Only set BASE_DIR if not already set
[ -z "$BASE_DIR" ] && export BASE_DIR=`cd "$PRGDIR" ; pwd`

#=== FUNCTION ==============================================================
# NAME:			_log
# DESCRIPTION:  echo the string passed as parameter if _DEBUG=true is set.
# PARAMETER 1:  the string to echo
#===========================================================================
_log() {
  if [ "$_DEBUG" == "true" ]; then
    echo 1>&2 "$@"
  fi
}

#=== FUNCTION ==============================================================
# NAME:			_get_pid
# DESCRIPTION:  returns the PID define in the runtime file if ti exist, 0
#				otherwise.
# PARAMETER 1:  the runtime file location
#===========================================================================
_get_pid() {
	RUNTIME_PID_FILE=$1
	if [ ! -e "${RUNTIME_PID_FILE}" ]; 
	then
        echo 0
	else
		local PID=`cat ${RUNTIME_PID_FILE} | awk '{print $1}'`
		echo ${PID}
    fi
}

#=== FUNCTION ==============================================================
# NAME:			_running
# DESCRIPTION:  checks if a process is running and set RUNNING variable to 1
# 				if it's live or to 0 otherwise.
# PARAMETER 1:  the process PID to check
#===========================================================================
_running() {
	RUNNING=0
	if [ -z "$PID" ]; then
		RUNNING=0
	else
		local PS_CMD=`ps p $PID | grep $PID`
		if [ ! -z "$PS_CMD" ]; then
			RUNNING=1
		else
			RUNNING=0
		fi
	fi
    return $RUNNING
}

#=== FUNCTION ==============================================================
# NAME:			_kill
# DESCRIPTION:  kills the given process.
# PARAMETER 1:  the process PID to kill.
#===========================================================================
_kill() {	
	local PID=$1	
	kill -9 ${PID}
}
